# -*- coding: utf-8 -*-
import urllib
import urllib2
import re
import xbmc
import xbmcplugin
import xbmcgui
import os
import sys

from utilities import *
from MediaWindow import MediaWindow, DirectoryItem

__plugin__ = "xbMako"

class Main:
    def __init__( self, name, url ):
        # get users preference
        self._get_settings()
        self.results = []
        # sort methods
        sortmethods = ( xbmcplugin.SORT_METHOD_LABEL, )
        # helper functions
        self.MediaWindow = MediaWindow( int( sys.argv[ 1 ] ), category=self.PluginCategory, content="tvshows", sortmethods=sortmethods, fanart=( self.settings[ "fanart_image" ], self.Fanart, ) )
        # fetch videos
        self.MediaWindow.end( self.List(name, url) )

    def _get_settings( self ):
        self.settings = {}
        self.PluginCategory = 'VOD' 
        self.settings[ "fanart_image" ] = ''
        self.Fanart = ''

    def get_mainSource(self, title, link, icon):
        RESOURCES_PATH = xbmc.translatePath( os.path.join( os.getcwd(), 'resources', 'media' ) )
        dirItem = DirectoryItem()
        dirItem.totalItems = 25
        dirItem.url = link
        dirItem.title = title
        
        try:
            icon = xbmc.translatePath( os.path.join( RESOURCES_PATH, icon ) )
        except:
            icon = 'DefaultFolder.png'
        dirItem.listitem = xbmcgui.ListItem( title, iconImage=icon, thumbnailImage=icon )
        dirItem.listitem.setInfo( "tvshow", { "Title": title } )
        dirItem.isFolder = True
        return dirItem

    def get_mainEpisode(self, title, link, icon):
        dirItem.listitem = xbmcgui.ListItem( title, iconImage=icon, thumbnailImage=icon )
        dirItem.listitem.setInfo( "tvshow", { "Title": title } )
        dirItem.isFolder = False
        return dirItem    
    
    def sort_shows(self, x, y):
        x_hebrewtitle = x[2]
        y_hebrewtitle = y[2]
            
        if (x_hebrewtitle > y_hebrewtitle):
            return 1
        elif (x_hebrewtitle < y_hebrewtitle):
            return -1
        else:
            return 0 

    def parseShows(self, source, regex):
        name = ""
        url = ""
        prev_englishtitle = ""
        matches=re.compile(regex).findall(source)

        counter = 0

        matches.sort(self.sort_shows)
        for link, englishtitle, hebrewtitle in matches:
##            if counter == 500: break
            if link.find('.htm') == -1:
                if (link[0:1] == "/"):
                    link = "http://www.mako.co.il" + link
                else:
                    link = "http://www.mako.co.il/" + link
##                #Not a special episode or movie
##                englishtitle = ""
##                hebrewtitle = ""
##                link = ""
##
##                try:
##                    englishtitle = re.compile('/.*?">').findall(match)[0]
##                    englishtitle = englishtitle[englishtitle.find('/', 2)+1:englishtitle.find('">')]
##
##                    hebrewtitle = re.compile('">.*?</a>').findall(match)[0]
##                    hebrewtitle = hebrewtitle[hebrewtitle.find('>', 0)+1:hebrewtitle.find('"</')-3]
##
##                    link = re.compile('"/.*?"').findall(match)[0]
##                    link = link[1:link.find('"', 2)]
##                    link = "http://www.mako.co.il" + link
##                except:
##                    englishtitle = re.compile('/.*?\'>').findall(match)[0]
##                    englishtitle = englishtitle[englishtitle.rfind('/')+1:englishtitle.find('\'>')]
##                    hebrewtitle = re.compile('\'>.*?</a>').findall(match)[0]
##                    hebrewtitle = hebrewtitle[hebrewtitle.find('>', 0)+1:hebrewtitle.find('\'</')-3]
##
##                    link = re.compile('\'.*?\'').findall(match)[0]
##                    link = link[1:link.find('\'', 2)]

                Debug( 'Found show: ' + englishtitle, True)    

                if (self.results.count(englishtitle) == 0):
                    self.results.append(englishtitle)

                    if not loadCache(englishtitle):
                        image = "DefaultFolder.png"
                        plot=""
                        try:
                            req = urllib2.Request(link)
                            req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                            response = urllib2.urlopen(req)
                            source=response.read()
                            response.close()
                            if (englishtitle=='eretz_nehederet'):
                                sourcefile = file(xbmc.translatePath( os.path.join( os.getcwd(), "eretz.htm" ) ), 'w')
                                sourcefile.write (source)
                                sourcefile.close()                                   
                            matches=re.compile('<div class="generic_rlbordered clearer">.*?<img src="(.*?)">.*?<h2>.*?</h2>.*?<p>(.*?)</p>', re.DOTALL).findall(source)
                            image, plot = matches[0]
                        except:
                            pass
                        counter = counter + 1
                        
                        saveCache(englishtitle, hebrewtitle, plot, image, '')
                    else:
                        hebrewtitle, plot, image, streamurl = loadCache(englishtitle)

                    self.addShow(englishtitle,link,1,image,hebrewtitle,plot)
        return True

    def parseSeasonsAndEpisodes(self, name, source, url=""):
        matches=re.compile('<li class=".*?" id="tab."><div class="tab"><div class="left"><div class="right"><a.href="(/mako-vod.*?/' + name + '-.*?)">(.*?)</a>').findall(source)

        try:
            temp = matches[0]
            Debug('Processing seasons', True)
            if len(matches) == 1:
                link, match = matches[0]
                source = ""
                
                req = urllib2.Request('http://www.mako.co.il' + link)
                req.add_header('User-Agent', ' Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')

                response = urllib2.urlopen(req)
                source = response.read()            # Holds the webpage that was read via the response.read() command.  
                response.close()                # Closes the connection after we have read the webpage.            
                self.parseSeasonsAndEpisodes(match.strip(), source, 'http://www.mako.co.il' + link)
            else:

                image = ""
                try:
                    banners=re.compile('<div class="generic_rlbordered clearer">.*?<img src="(.*?)">.*?<h2>.*?</h2>', re.DOTALL).findall(source)
                    image = banners[0]
                except:
                    pass
                
                for link, match in sorted(matches):
                    Debug( 'Season (' + match + ')...', True)
                    if match.isdigit():
                        season = match.strip()
                        match = 'עונה' + match
                    else:
                        season = ""
                        match = 'עונה ' + match
                    self.addSeason(match.strip(),'http://www.mako.co.il' + link,1,image, season)
        except:
            Debug( 'Processing Episodes', True)
            
            if url == "":
                    matches=re.compile('<a href="(.*?)">.*?<img src="(.*?)">.*?<strong>(.*?)</strong>(.*?)</a>', re.DOTALL).findall(source)
            else:
                    matches=re.compile('<a href="(' + url.replace('http://www.mako.co.il','') + '/.*?)">.*?<img src="(.*?)">.*?<strong>(.*?)</strong>(.*?)</a>', re.DOTALL).findall(source)

            for link, image, episode, description in matches:
                title = episode
                streamurl = ""
                filename = link.replace('.', ''). replace('/','').replace(':','')
                if not loadCache(filename):
                    Debug( 'Trying to parse episode: ' + 'http://www.mako.co.il' + link, True)                    
                    req = urllib2.Request("http://www.mako.co.il" + link)
                    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                    response = urllib2.urlopen(req)
                    source=response.read()
                    response.close()

                    
                    #match=re.compile('<iframe scrolling="no" src="(.*?)" width.*?>').findall(source)
                    #match=re.compile('VODManager\.initialize\(\'(.*?)\'\);').findall(source) #SKING del
                    match=re.compile('VODManager\.loadPlayerImage\(\'(.*?)&th').findall(source) #SKING add
                    for url in match:
                        Debug( 'Found url for parsing: ' + url, True)
                        alturl = ""
                        try:
                            alturl = re.compile("(http://.*?)'", re.DOTALL).findall(url)[0]
                            url = alturl
                        except:
                            pass
                        try:
                            streamurl=url
                            if streamurl.find("'") > -1:
                                streamurl=re.compile("(.*?)'").findall(streamurl)[0]                            
                            if streamurl != '':                        
                                saveCache(filename, title, '', image, streamurl)
                        except:
                            print 'Exception: ' + url
                else:
                    title, plot, image, streamurl = loadCache(filename)
                Debug( 'Episode, Link: ' + link + '), Image: ' + image + ', Stream: ' + streamurl, True)
                if streamurl != '':
                    self.addEpisode (title, streamurl, image, episode.strip())
                           
    def List(self,name, url):
        print url
        source = ""
        
        req = urllib2.Request(url)
        req.add_header('User-Agent', ' Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')

        response = urllib2.urlopen(req)
        source = response.read()            # Holds the webpage that was read via the response.read() command.  
        response.close()                # Closes the connection after we have read the webpage.

        if name == "" or name == "MAKO.CO.IL":
            sourcefile = file(xbmc.translatePath( os.path.join( os.getcwd(), "test.htm" ) ), 'w')
            sourcefile.write (source)
            sourcefile.close()            
            
            Debug( 'Shows', True)   
            self.parseShows(source, '<li ><a href="/(.*?mako-vod-.*?/(.*?))">(.*?)</a></li>')
            self.parseShows(source, '<li  class=" last5 last4"><a href="(.*?/mako-vod-.*?/(.*?))">(.*?)</a></li>')            
        else:
            Debug('Seasons', True)
            self.parseSeasonsAndEpisodes(name, source, url)
        return True
            
    def addShow(self,name,url,mode,iconimage, name_fixed="",plot=""):
        if name_fixed=="": name_fixed = name
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&name_fixed="+urllib.quote_plus(name_fixed)
        ok=True
        liz=xbmcgui.ListItem(label=name_fixed, label2=name, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "tvshowtitle": name , "plot": plot } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True,totalItems=10)
        #self.MediaWindow.add(self.get_mainSource(name_fixed,u, iconimage))
        return ok

    def addSeason(self,name,url,mode,iconimage, name_fixed="",season=""):
        if name_fixed=="": name_fixed = name
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&name_fixed="+urllib.quote_plus(name_fixed)
        ok=True
        liz=xbmcgui.ListItem(label=name_fixed, label2=name, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "tvshowtitle": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True,totalItems=10)
        #self.MediaWindow.add(self.get_mainSource(name_fixed,u, iconimage))
        return ok

    def addEpisode(self, name,url,iconimage,episode=""):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        #self.MediaWindow.add(self.get_mainEpisode(name,url, iconimage))
        return ok
